package cn.edu.xmu.software.streamplayer;

import cn.edu.xmu.software.streamplayer.aidl.PlayEngineInterface;
import cn.edu.xmu.software.streamplayer.service.PlayEngine;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PlayerActivity extends Activity {
	/** Called when the activity is first created. */
	public final String TAG = "playerActivity";
	private PlayEngineInterface peInterface;
	public final String url = "http://188.165.12.66:8000";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		Button button1 = (Button) findViewById(R.id.start);
		button1.setOnClickListener(startIt);
		Button button2 = (Button) findViewById(R.id.pause);
		button2.setOnClickListener(pauseIt);
		Button button3 = (Button) findViewById(R.id.stop);
		button3.setOnClickListener(stopIt);
		this.bindService(new Intent(PlayerActivity.this, PlayEngine.class),
				serviceConnection, Context.BIND_AUTO_CREATE);
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			peInterface = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG, "service connected!");
			peInterface = PlayEngineInterface.Stub
					.asInterface((IBinder) service);
			try {
				peInterface.addSong(url);
				Log.i(TAG, "add song to service!");
			} catch (RemoteException e) {
				Log.e(TAG, "add song failed!");
				e.printStackTrace();
			}
		}
	};
	private OnClickListener startIt = new OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				peInterface.play();
				Log.i(TAG, "start to play!");
			} catch (RemoteException e) {
				Log.e(TAG, "play error!");
				e.printStackTrace();
			}
		}
	};
	private OnClickListener pauseIt = new OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				peInterface.pause();
				Log.i(TAG, "pause play!");
			} catch (RemoteException e) {
				Log.e(TAG, "pause error!");
				e.printStackTrace();
			}
		}
	};
	private OnClickListener stopIt = new OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				peInterface.stop();
				Log.i(TAG, "stop play!");
			} catch (RemoteException e) {
				Log.e(TAG, "stop error!");
				e.printStackTrace();
			}
		}
	};

	public void onDestroy() {
		Log.d(TAG, "onDestroy!");
		super.onDestroy();
		unbindService(serviceConnection);
	}
}